package com.party.web.web.controller.gatherInfo;

import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.circle.CircleMemberTag;
import com.party.core.model.circle.CircleTag;
import com.party.core.model.competition.CompetitionBusiness;
import com.party.core.model.competition.CompetitionProject;
import com.party.core.model.gatherInfo.GatherInfoGroup;
import com.party.core.model.gatherInfo.GatherInfoMember;
import com.party.core.model.gatherInfo.GatherInfoProject;
import com.party.core.service.circle.ICircleMemberTagService;
import com.party.core.service.circle.ICircleTagService;
import com.party.core.service.circle.biz.CircleBizService;
import com.party.core.service.circle.biz.CircleMemberBizService;
import com.party.core.service.competition.ICompetitionBusinessService;
import com.party.core.service.competition.ICompetitionGroupService;
import com.party.core.service.competition.ICompetitionMemberService;
import com.party.core.service.competition.ICompetitionProjectService;
import com.party.core.service.competition.biz.CompetitionProjectBizService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.gatherInfo.IGatherInfoGroupService;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.member.IMemberGroupService;
import com.party.web.biz.circle.CircleBizNewService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.gatherInfo.ItineraryBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.gatherInfo.GatherInfoProjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 人员信息采集项目
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("gatherInfo/project")
public class GatherInfoProjectController {

	@Autowired
	private IGatherInfoProjectService gatherInfoProjectService;
	@Autowired
	private IGatherInfoMemberService gatherInfoMemberService;
	@Autowired
	private IGatherInfoGroupService gatherInfoGroupService;
	@Autowired
	private FileBizService fileBizService;
	@Autowired
	private ICompetitionBusinessService competitionBusinessService;
	@Autowired
	private ICompetitionProjectService competitionProjectService;
	@Autowired
	private ICompetitionMemberService competitionMemberService;
	@Autowired
	private ICompetitionGroupService competitionGroupService;
	@Autowired
	private CompetitionProjectBizService competitionProjectBizService;
    @Autowired
    private CosBizService cosBizService;
	@Autowired
	private ICircleTagService circleTagService;
	@Autowired
	private ICircleMemberTagService circleMemberTagService;
	@Autowired
	private CircleMemberBizService circleMemberBizService;
	@Autowired
	private CircleBizService circleBizService;
	@Autowired
	private ItineraryBizService itineraryBizService;
	@Autowired
	private CircleBizNewService circleBizNewService;
	@Autowired
	private IMemberGroupService memberGroupService;

    Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 列表
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView list(Page page, GatherInfoProject project, CommonInput commonInput) {
		page.setLimit(15);
		project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		ModelAndView mv = new ModelAndView("gatherInfo/projectList");

		String memberId = RealmUtils.getCurrentUser().getId();
		Map<String, Object> params = CommonInput.appendParams(commonInput);
		List<String> orgIds = memberGroupService.getChildWithMy(memberId);
		params.put("orgIds", orgIds);

		List<GatherInfoProject> memberInfoProjects = gatherInfoProjectService.webListPage(project, params, page);
        List<GatherInfoProjectOutput> outputs = LangUtils.transform(memberInfoProjects, input -> {
			String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "gatherInfo");
            GatherInfoProjectOutput output = GatherInfoProjectOutput.transform(input);
            int totalNum = gatherInfoMemberService.getCountByProject(input.getId());
            output.setTotalNum(totalNum);

            GatherInfoGroup t = new GatherInfoGroup();
            t.setProjectId(input.getId());
            List<GatherInfoGroup> groups = gatherInfoGroupService.list(t);
            output.setGroupNum(groups.size());

            // 基本信息二维码
            String fileName = "base_" + input.getId();
            String baseQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            output.setBaseQrCodeUrl(baseQrCodeUrl);

            // 保险信息二维码
            fileName = "insurance_" + input.getId();
            baseQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            output.setInsuranceQrCodeUrl(baseQrCodeUrl);

            // 行程信息二维码
            fileName = "itinerary_" + input.getId();
            baseQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + fileName);
            output.setItineraryQrCodeUrl(baseQrCodeUrl);
            return output;
        });

		mv.addObject("projectList", outputs);
		mv.addObject("input", commonInput);
		mv.addObject("project", project);
		mv.addObject("page", page);
		return mv;
	}

	/**
	 * 创建圈子
	 *
	 * @param infoId
	 * @return
	 */
	@DataControl
	@Transactional
	@ResponseBody
	@RequestMapping(value = "createCircle")
	public AjaxResult createCircle(@ControlParam(table = "gather_info_project", column = "create_by") String infoId, String type) {
		try {
			GatherInfoMember memberInfo = new GatherInfoMember();
			memberInfo.setProjectId(infoId);
			GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(infoId);
			if (null == type) {
				type = "2";
			}
			//信息收集项目下的会员
			GatherInfoMember gatherInfoMember = new GatherInfoMember();
			GatherInfoGroup gatherInfoGroup = new GatherInfoGroup();
			gatherInfoMember.setProjectId(infoId);
			List<GatherInfoMember> gatherInfoMembers = gatherInfoMemberService.list(gatherInfoMember);
			List<Map<String, Object>> memberInfos = gatherInfoMemberService.webListPage(memberInfo, Maps.newHashMap(), null);
			List<String> memberIds = new ArrayList<String>();
			memberIds.add(gatherInfoProject.getCreateBy());
			String circleId = circleBizService.createCircleBusinessGatherinfo(infoId, gatherInfoProject, type);
			circleMemberBizService.circleMemberManageGatherinfo(gatherInfoMembers, circleId, memberIds, gatherInfoProject.getCreateBy());
			//ExecutorService transferThreadPool = Executors.newFixedThreadPool(2);
			//transferThreadPool.execute();
			gatherInfoGroup.setProjectId(infoId);
			List<GatherInfoGroup> groups = gatherInfoGroupService.list(gatherInfoGroup);
			for (GatherInfoGroup gi : groups) {
				CircleTag circleTag = new CircleTag();
				circleTag.setCircle(circleId);
				circleTag.setTagName(gi.getGroupName());
				try {
					int sort = Integer.parseInt(gi.getGroupNo());
					circleTag.setSort(sort);
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				List<CircleTag> circleTagList = circleTagService.list(circleTag);
				if (circleTagList.size() == 0) {
					circleTagService.insert(circleTag);
				}
			}
			for (Map<String, Object> GMember : memberInfos) {
				CircleTag circleTag = new CircleTag();
				String id = (String) GMember.get("memberId");
				String gropName = (String) GMember.get("groupName");
				if (gropName != "" && null != gropName) {
					CircleMemberTag circleMemberTag = new CircleMemberTag();
					circleMemberTag.setCircle(circleId);
					circleMemberTag.setMember(id);
					circleTag.setCircle(circleId);
					circleTag.setTagName(gropName);
					List<CircleMemberTag> cmList = circleMemberTagService.list(circleMemberTag);
					if (cmList.size() == 0) {
						List<CircleTag> ct = circleTagService.list(circleTag);
						if (ct.size() > 0) {
							circleMemberTag.setTag(ct.get(0).getId());
							circleMemberTagService.insert(circleMemberTag);
						}
					}
				}
			}

			circleBizNewService.uploadQrCode(gatherInfoProject.getCreateBy(), circleId);
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("生成圈子异常", e);
			return AjaxResult.error("生成圈子异常");
		}
	}

	/**
	 * 新增/编辑表单
	 * 
	 * @param id
	 * @return
	 */
	@DataControl
	@RequestMapping("toForm")
	public ModelAndView toForm(@ControlParam(table = "gather_info_project", column = "create_by", isRequired = false)String id) {
		ModelAndView mv = new ModelAndView("gatherInfo/projectForm");
		if (StringUtils.isNotEmpty(id)) {
			GatherInfoProject project = gatherInfoProjectService.get(id);
			mv.addObject("project", project);
		}
		return mv;
	}

	/**
	 * 保存
	 *
	 * @param project
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public AjaxResult save(GatherInfoProject project) {
		try {
			String memberId = RealmUtils.getCurrentUser().getId();
			if (StringUtils.isEmpty(project.getId())) {
				project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
				project.setCreateBy(memberId);
				project.setUpdateBy(memberId);
				gatherInfoProjectService.insert(project);
			} else {
				GatherInfoProject t = gatherInfoProjectService.get(project.getId());
				MyBeanUtils.copyBeanNotNull2Bean(project, t);
				gatherInfoProjectService.update(t);

				memberId = t.getCreateBy();
			}

			itineraryBizService.uploadQrCode(memberId, project.getId());
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("保存人员信息收集项目异常", e);
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@DataControl
	@ResponseBody
	@RequestMapping("delete")
	public AjaxResult delete(@ControlParam(table = "gather_info_project", column = "create_by")String id) {
		List<GatherInfoMember> memberInfoForms = gatherInfoMemberService.findByProject(id);
		GatherInfoGroup t = new GatherInfoGroup();
		t.setProjectId(id);
		List<GatherInfoGroup> gatherInfoGroups = gatherInfoGroupService.list(t);
		if (memberInfoForms.size() > 0) {
			return AjaxResult.error("该项目下已有收集人员信息，不能删除");
		} else if (gatherInfoGroups.size() > 0) {
			return AjaxResult.error("该项目下已有小组，不能删除");
		} else {
			gatherInfoProjectService.delete(id);
			return AjaxResult.success();
		}
	}

	/**
	 * 同步生成圈子
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("syncCircle")
	public AjaxResult syncCircle(String id) {
		return AjaxResult.success();
	}

	/**
	 * 同步生成赛事项目
	 * 
	 * @param id
	 * @return
	 */
	@DataControl
	@ResponseBody
	@RequestMapping("syncCompetition")
	public AjaxResult syncCompetition(@ControlParam(table = "gather_info_project", column = "create_by")String id, String type) {
		try {
			GatherInfoProject gProject = gatherInfoProjectService.get(id);
			String cProjectId = "";
			String currentId = gProject.getCreateBy();
			CompetitionBusiness cBusiness = competitionBusinessService.findByBusinessId(id, type);
			if (cBusiness == null) {
                cBusiness = new CompetitionBusiness();
                cBusiness.setBusinessId(id);
                cBusiness.setType(type);
                cBusiness.setCreateBy(currentId);
                cBusiness.setUpdateBy(currentId);
                String competitionId = competitionProjectBizService.createCompetition(gProject.getTitle(), gProject.getCreateBy());
                cBusiness.setCompetitionId(competitionId);
                competitionBusinessService.insert(cBusiness);

                cProjectId = competitionId;
            } else {
                String competitionId = cBusiness.getCompetitionId();
                CompetitionProject cProject = competitionProjectService.get(competitionId);
                if (cProject == null) {
                    competitionId = competitionProjectBizService.createCompetition(gProject.getTitle(), gProject.getCreateBy());
                    cBusiness.setCompetitionId(competitionId);
                    competitionBusinessService.update(cBusiness);

                    cProjectId = competitionId;
                } else {
                    cProject.setTitle(gProject.getTitle());
                    competitionProjectService.update(cProject);

                    cProjectId = cProject.getId();
                }
            }

			competitionProjectBizService.insertCompetitionMember(cProjectId, gProject.getId(), gProject.getCreateBy());

			try {
				String memberId = gProject.getCreateBy();
				String filePath = fileBizService.getUploadCIPath(memberId, "competition");
				String content = "competition/all_person_rank.html?projectId=" + gProject.getId();
				fileBizService.uploadCloudOut(gProject.getId(), filePath, content, memberId);
			} catch (Exception e) {
				logger.error("生成赛事成绩项目二维码异常", e);
			}
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("生成赛事项目异常", e);
			return AjaxResult.error("生成赛事项目异常");
		}
	}

}
